const db = uniCloud.database();
const dbCmd = db.command;
const paymentCollection = db.collection('payment');

module.exports = {
  _before: function() {
    // 通用前置处理
  },
  
  /**
   * 获取缴费记录列表
   * @param {Object} params - 查询参数
   * @param {String} params.student_id - 学生ID（可选）
   * @param {String} params.course_id - 课程ID（可选）
   * @param {String} params.enrollment_id - 报名ID（可选）
   * @param {Number} params.status - 状态（可选）
   * @param {String} params.start_date - 开始日期（可选）
   * @param {String} params.end_date - 结束日期（可选）
   * @param {Number} params.page - 页码
   * @param {Number} params.pageSize - 每页数量
   * @returns {Object} 缴费记录列表和总数
   */
  async getPaymentList(params = {}) {
    const { 
      student_id, 
      course_id, 
      enrollment_id, 
      status, 
      start_date, 
      end_date,
      page = 1, 
      pageSize = 10 
    } = params;
    
    // 构建查询条件
    const query = {};
    if (student_id) query.student_id = student_id;
    if (course_id) query.course_id = course_id;
    if (enrollment_id) query.enrollment_id = enrollment_id;
    if (status !== undefined) query.status = status;
    
    // 日期范围查询
    if (start_date && end_date) {
      const startDate = new Date(start_date);
      startDate.setHours(0, 0, 0, 0);
      
      const endDate = new Date(end_date);
      endDate.setHours(23, 59, 59, 999);
      
      query.payment_date = dbCmd.gte(startDate).and(dbCmd.lte(endDate));
    }
    
    // 查询总数
    const countResult = await paymentCollection.where(query).count();
    const total = countResult.total;
    
    // 查询分页数据
    const list = await paymentCollection
      .aggregate()
      .match(query)
      .lookup({
        from: 'student',
        localField: 'student_id',
        foreignField: '_id',
        as: 'student'
      })
      .lookup({
        from: 'course',
        localField: 'course_id',
        foreignField: '_id',
        as: 'course'
      })
      .project({
        _id: 1,
        student_id: 1,
        course_id: 1,
        enrollment_id: 1,
        amount: 1,
        payment_date: 1,
        period_start: 1,
        period_end: 1,
        payment_method: 1,
        status: 1,
        remarks: 1,
        create_date: 1,
        update_date: 1,
        student: { $arrayElemAt: ['$student', 0] },
        course: { $arrayElemAt: ['$course', 0] }
      })
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .sort({
        payment_date: -1
      })
      .end()
      .then(res => res.data);
    
    return {
      list,
      total,
      page,
      pageSize
    };
  },
  
  /**
   * 获取缴费记录详情
   * @param {String} id - 缴费记录ID
   * @returns {Object} 缴费记录详情
   */
  async getPaymentDetail(id) {
    if (!id) throw new Error('缴费记录ID不能为空');
    
    const payment = await paymentCollection
      .aggregate()
      .match({
        _id: id
      })
      .lookup({
        from: 'student',
        localField: 'student_id',
        foreignField: '_id',
        as: 'student'
      })
      .lookup({
        from: 'course',
        localField: 'course_id',
        foreignField: '_id',
        as: 'course'
      })
      .lookup({
        from: 'enrollment',
        localField: 'enrollment_id',
        foreignField: '_id',
        as: 'enrollment'
      })
      .project({
        _id: 1,
        student_id: 1,
        course_id: 1,
        enrollment_id: 1,
        amount: 1,
        payment_date: 1,
        period_start: 1,
        period_end: 1,
        payment_method: 1,
        status: 1,
        remarks: 1,
        create_date: 1,
        update_date: 1,
        student: { $arrayElemAt: ['$student', 0] },
        course: { $arrayElemAt: ['$course', 0] },
        enrollment: { $arrayElemAt: ['$enrollment', 0] }
      })
      .end()
      .then(res => res.data[0]);
    
    if (!payment) throw new Error('缴费记录不存在');
    
    return payment;
  },
  
  /**
   * 创建缴费记录
   * @param {Object} data - 缴费数据
   * @returns {Object} 创建结果
   */
  async createPayment(data) {
    // 验证必填字段
    const { 
      student_id, 
      course_id, 
      enrollment_id, 
      amount, 
      payment_date,
      period_start,
      period_end,
      payment_method
    } = data;
    
    if (!student_id) throw new Error('学生ID不能为空');
    if (!course_id) throw new Error('课程ID不能为空');
    if (!enrollment_id) throw new Error('报名ID不能为空');
    if (amount === undefined || amount <= 0) throw new Error('缴费金额必须大于0');
    if (!payment_date) throw new Error('缴费日期不能为空');
    if (!period_start) throw new Error('缴费周期开始日期不能为空');
    if (!period_end) throw new Error('缴费周期结束日期不能为空');
    if (![1, 2, 3, 4].includes(payment_method)) throw new Error('支付方式不正确');
    
    // 检查报名记录是否存在
    const enrollment = await db.collection('enrollment')
      .doc(enrollment_id)
      .get()
      .then(res => res.data[0]);
    
    if (!enrollment) throw new Error('报名记录不存在');
    if (enrollment.status !== 1) throw new Error('报名记录已取消，无法创建缴费记录');
    
    // 检查学生和课程ID是否与报名记录匹配
    if (enrollment.student_id !== student_id) {
      throw new Error('学生ID与报名记录不匹配');
    }
    
    if (enrollment.course_id !== course_id) {
      throw new Error('课程ID与报名记录不匹配');
    }
    
    // 验证日期
    const startDate = new Date(period_start);
    const endDate = new Date(period_end);
    
    if (startDate > endDate) {
      throw new Error('缴费周期开始日期不能晚于结束日期');
    }
    
    // 创建缴费记录
    const result = await paymentCollection.add({
      ...data,
      status: data.status || 1, // 默认为已缴费
      create_date: new Date(),
      update_date: new Date()
    });
    
    return {
      id: result.id,
      success: true
    };
  },
  
  /**
   * 更新缴费记录
   * @param {String} id - 缴费记录ID
   * @param {Object} data - 更新数据
   * @returns {Object} 更新结果
   */
  async updatePayment(id, data) {
    if (!id) throw new Error('缴费记录ID不能为空');
    
    // 检查缴费记录是否存在
    const payment = await paymentCollection.doc(id).get().then(res => res.data[0]);
    if (!payment) throw new Error('缴费记录不存在');
    
    // 检查并验证日期范围
    if (data.period_start && data.period_end) {
      const startDate = new Date(data.period_start);
      const endDate = new Date(data.period_end);
      
      if (startDate > endDate) {
        throw new Error('缴费周期开始日期不能晚于结束日期');
      }
    }
    
    // 更新缴费记录
    await paymentCollection.doc(id).update({
      ...data,
      update_date: new Date()
    });
    
    return {
      id,
      success: true
    };
  },
  
  /**
   * 取消缴费记录
   * @param {String} id - 缴费记录ID
   * @returns {Object} 取消结果
   */
  async cancelPayment(id) {
    if (!id) throw new Error('缴费记录ID不能为空');
    
    // 检查缴费记录是否存在
    const payment = await paymentCollection.doc(id).get().then(res => res.data[0]);
    if (!payment) throw new Error('缴费记录不存在');
    
    // 检查是否有关联的退费记录
    const refundCount = await db.collection('refund')
      .where({
        payment_id: id,
        status: dbCmd.neq(0)
      })
      .count();
    
    if (refundCount.total > 0) {
      throw new Error('该缴费记录已有关联的退费记录，无法取消');
    }
    
    // 取消缴费记录
    await paymentCollection.doc(id).update({
      status: 0,
      update_date: new Date()
    });
    
    return {
      id,
      success: true
    };
  },
  
  /**
   * 获取欠费学生列表
   * @returns {Array} 欠费学生列表
   */
  async getUnpaidStudents() {
    // 获取所有有效的报名记录
    const enrollments = await db.collection('enrollment')
      .aggregate()
      .match({
        status: 1
      })
      .lookup({
        from: 'student',
        localField: 'student_id',
        foreignField: '_id',
        as: 'student'
      })
      .lookup({
        from: 'course',
        localField: 'course_id',
        foreignField: '_id',
        as: 'course'
      })
      .project({
        _id: 1,
        student_id: 1,
        course_id: 1,
        fee: 1,
        student: { $arrayElemAt: ['$student', 0] },
        course: { $arrayElemAt: ['$course', 0] }
      })
      .end()
      .then(res => res.data);
    
    // 获取已缴费总额
    const enrollmentIds = enrollments.map(e => e._id);
    const payments = await paymentCollection
      .where({
        enrollment_id: dbCmd.in(enrollmentIds),
        status: 1 // 已缴费状态
      })
      .field({
        enrollment_id: true,
        amount: true
      })
      .get()
      .then(res => res.data);
    
    // 计算每个报名记录的已缴费总额
    const paymentMap = {};
    payments.forEach(payment => {
      if (!paymentMap[payment.enrollment_id]) {
        paymentMap[payment.enrollment_id] = 0;
      }
      paymentMap[payment.enrollment_id] += payment.amount;
    });
    
    // 筛选出欠费的学生
    const unpaidStudents = enrollments.filter(enrollment => {
      const paidAmount = paymentMap[enrollment._id] || 0;
      return paidAmount < enrollment.fee;
    }).map(enrollment => {
      const paidAmount = paymentMap[enrollment._id] || 0;
      const unpaidAmount = enrollment.fee - paidAmount;
      
      return {
        enrollment_id: enrollment._id,
        student_id: enrollment.student_id,
        course_id: enrollment.course_id,
        student_name: enrollment.student?.name || '',
        course_name: enrollment.course?.name || '',
        total_fee: enrollment.fee,
        paid_amount: paidAmount,
        unpaid_amount: unpaidAmount
      };
    });
    
    return unpaidStudents;
  },
  
  /**
   * 根据报名ID获取缴费记录
   * @param {String} enrollment_id - 报名ID
   * @returns {Object} 缴费记录和统计信息
   */
  async getPaymentsByEnrollment(enrollment_id) {
    if (!enrollment_id) throw new Error('报名ID不能为空');
    
    // 获取报名记录
    const enrollment = await db.collection('enrollment')
      .aggregate()
      .match({
        _id: enrollment_id
      })
      .lookup({
        from: 'student',
        localField: 'student_id',
        foreignField: '_id',
        as: 'student'
      })
      .lookup({
        from: 'course',
        localField: 'course_id',
        foreignField: '_id',
        as: 'course'
      })
      .project({
        _id: 1,
        student_id: 1,
        course_id: 1,
        fee: 1,
        discount: 1,
        student: { $arrayElemAt: ['$student', 0] },
        course: { $arrayElemAt: ['$course', 0] }
      })
      .end()
      .then(res => res.data[0]);
    
    if (!enrollment) throw new Error('报名记录不存在');
    
    // 获取缴费记录
    const payments = await paymentCollection
      .where({
        enrollment_id,
        status: dbCmd.neq(0) // 非取消状态
      })
      .orderBy('payment_date', 'desc')
      .get()
      .then(res => res.data);
    
    // 计算总缴费金额
    const totalPaid = payments.reduce((sum, payment) => sum + payment.amount, 0);
    
    // 计算剩余应缴费金额
    const remainingFee = enrollment.fee - totalPaid;
    
    return {
      enrollment,
      payments,
      stats: {
        total_fee: enrollment.fee,
        discount: enrollment.discount,
        total_paid: totalPaid,
        remaining_fee: remainingFee
      }
    };
  },
  
  /**
   * 获取学生的所有缴费记录和统计信息
   * @param {String} student_id - 学生ID
   * @returns {Object} 缴费记录和统计信息
   */
  async getStudentPayments(student_id) {
    if (!student_id) throw new Error('学生ID不能为空');
    
    // 获取学生信息
    const student = await db.collection('student')
      .doc(student_id)
      .get()
      .then(res => res.data[0]);
    
    if (!student) throw new Error('学生不存在');
    
    // 获取学生的所有报名记录
    const enrollments = await db.collection('enrollment')
      .aggregate()
      .match({
        student_id,
        status: 1 // 有效报名
      })
      .lookup({
        from: 'course',
        localField: 'course_id',
        foreignField: '_id',
        as: 'course'
      })
      .project({
        _id: 1,
        course_id: 1,
        fee: 1,
        discount: 1,
        course: { $arrayElemAt: ['$course', 0] }
      })
      .end()
      .then(res => res.data);
    
    // 获取所有缴费记录
    const payments = await paymentCollection
      .where({
        student_id,
        status: dbCmd.neq(0) // 非取消状态
      })
      .orderBy('payment_date', 'desc')
      .get()
      .then(res => res.data);
    
    // 按课程分组缴费记录
    const coursesPayments = {};
    
    enrollments.forEach(enrollment => {
      const courseId = enrollment.course_id;
      const courseName = enrollment.course?.name || '未知课程';
      
      if (!coursesPayments[courseId]) {
        coursesPayments[courseId] = {
          course_id: courseId,
          course_name: courseName,
          enrollment_id: enrollment._id,
          total_fee: enrollment.fee,
          discount: enrollment.discount,
          payments: [],
          total_paid: 0,
          remaining_fee: enrollment.fee
        };
      }
    });
    
    // 将缴费记录分配到相应课程
    payments.forEach(payment => {
      const courseId = payment.course_id;
      
      if (coursesPayments[courseId]) {
        coursesPayments[courseId].payments.push(payment);
        coursesPayments[courseId].total_paid += payment.amount;
        coursesPayments[courseId].remaining_fee -= payment.amount;
      }
    });
    
    // 计算总计数据
    const totalFee = enrollments.reduce((sum, e) => sum + e.fee, 0);
    const totalDiscount = enrollments.reduce((sum, e) => sum + (e.discount || 0), 0);
    const totalPaid = payments.reduce((sum, p) => sum + p.amount, 0);
    const totalRemaining = totalFee - totalPaid;
    
    return {
      student,
      courses_payments: Object.values(coursesPayments),
      all_payments: payments,
      stats: {
        total_fee: totalFee,
        total_discount: totalDiscount,
        total_paid: totalPaid,
        total_remaining: totalRemaining
      }
    };
  }
};